package com.sinheldrin.musicplayer.fields
{
	import com.sinheldrin.musicplayer.reader.XmlReader;
	import com.sinheldrin.musicplayer.writer.XmlWriter;
	
	import flash.filesystem.File;

	public class FieldsController
	{
		private static const FILENAME:String = "fields.xml";
		
		public function FieldsController()
		{
			_model = new FieldsModel();
		}
		
		private var _model:FieldsModel = null;
		public function get model():FieldsModel
		{
			return _model;
		}

		public function addFieldClass(fieldClass:FieldClass):void
		{
			_model.classes.addItem(fieldClass);
			if (fieldClass.id > _model.maxId)
				_model.maxId = fieldClass.id;
		}
		
		public function addNewFieldClass(fieldClass:FieldClass):void
		{
			fieldClass.id = ++(_model.maxId);
			_model.classes.addItem(fieldClass);
		}
		
		public function getFieldClassById(id:int):FieldClass
		{
			for each (var fieldClass:FieldClass in model.classes)
			{
				if (fieldClass.id == id)
					return fieldClass;
			}
			return null;
		}
		
		public function load():void
		{
			var reader:XmlReader = new XmlReader();
			var file:File = File.applicationStorageDirectory.resolvePath(FILENAME);
			if (file.exists)
				reader.readFieldClasses(this, file);
			else
				createDefaultClasses();
		}
		
		public function save():void
		{
			var writer:XmlWriter = new XmlWriter();
			writer.writeFieldClasses(_model, File.applicationStorageDirectory, FILENAME);
		}
		
		private function createDefaultClasses():void
		{
			var fieldClass:FieldClass = new FieldClass();
			fieldClass.name = "Author";
			fieldClass.isDefault = true;
			addNewFieldClass(fieldClass);
			
			fieldClass = new FieldClass();
			fieldClass.name = "Title";
			fieldClass.isDefault = true;
			addNewFieldClass(fieldClass);
		}
	}
}